package com.qianbao.finance.sync.modules.elasticsearch.scheduling;

import com.alibaba.fastjson.JSON;
import com.qianbao.finance.sync.modules.elasticsearch.model.SyncMappingConfig;
import com.qianbao.finance.sync.modules.elasticsearch.service.MappingService;
import com.qianbao.finance.sync.modules.elasticsearch.websocket.server.ChatRoom;
import com.qianbao.finance.sync.modules.elasticsearch.websocket.server.ShareBean;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;

@Component
public class SyncBroadcastScheduling implements Runnable {

    private static final Logger logger = LoggerFactory.getLogger(SyncBroadcastScheduling.class);
    private static final String ROOMNAME = "r1";
    private static final String GROUPNAME = "g2";

    @Resource
    private MappingService mappingService;

    @Scheduled(fixedDelay = 10000)
    @Override
    public void run() {
        logger.debug("run sync broadcast");
        ChatRoom chatRoom;
        try {
            List<SyncMappingConfig> syncMappingConfigList = mappingService.listDbEsMapping();
            if ((chatRoom = ShareBean.getInstance().getChatRoom().get(ROOMNAME)) != null){
                chatRoom.broadcastMessage(GROUPNAME, JSON.toJSONString(syncMappingConfigList));
            }
        } catch (Exception e) {
            logger.error("SyncBroadcast_scheduled异常！", e);
        }
    }

}
